package com.neuronbit.businessflow.runtime;

import com.neuronbit.businessflow.runtime.lifecycle.FlowLifecycleHook;
import com.neuronbit.businessflow.runtime.lifecycle.StepLifecycleHook;
import com.neuronbit.businessflow.runtime.repo.BusinessFlowRepository;
import org.springframework.context.ApplicationContext;

import java.util.Collection;
import java.util.Map;

import static java.util.Collections.emptySet;

/**
 * The type Spring step bean provider.
 */
public class SpringStepBeanProvider implements StepBeanProvider {
    //FIXME shunyun 2024/7/29: 去掉ApplicationContext的方式
    private final ApplicationContext applicationContext;

    public SpringStepBeanProvider(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * Gets bean.
     *
     * @param <T>   the type parameter
     * @param clazz the clazz
     * @return the bean
     */
    @Override
    public <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * Gets flow hooks.
     *
     * @return the flow hooks
     */
    @Override
    public Collection<FlowLifecycleHook> getFlowHooks() {
        Map<String, FlowLifecycleHook> beansOfType = applicationContext.getBeansOfType(FlowLifecycleHook.class);
        if (beansOfType.isEmpty()) {
            return emptySet();
        }
        return beansOfType.values();
    }

    /**
     * Gets step hooks.
     *
     * @return the step hooks
     */
    @Override
    public Collection<StepLifecycleHook> getStepHooks() {
        Map<String, StepLifecycleHook> beansOfType = applicationContext.getBeansOfType(StepLifecycleHook.class);
        if (beansOfType.isEmpty()) {
            return emptySet();
        }
        return beansOfType.values();
    }

    @Override
    public BusinessFlowRepository getRepository() {
        return applicationContext.getBean(BusinessFlowRepository.class);
    }
}
